package com.delivery.deliverysystem.exception;


import com.delivery.deliverysystem.common.ServerResponse;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * spring boot 异常处理：主要处理shiro注解抛出的异常,统一返回异常结果（json数据）给前端验证
 */
@RestControllerAdvice //异常处理的注解
public class BaseExceptionHandler {

    /**
     *处理未授权的异常
     */
    @ExceptionHandler(value = AuthorizationException.class)
    public ServerResponse returnErrorMsg(HttpServletRequest request, HttpServletResponse response, AuthorizationException exception){
        return ServerResponse.createUnAuthorizedError("您没有权限");
    }

    /**
     * 处理未登录的异常
     */
    @ExceptionHandler(value = UnauthenticatedException.class)
    public ServerResponse returnUnLoginErrorMsg(HttpServletRequest request, HttpServletResponse response, UnauthenticatedException exception){
        return ServerResponse.createUnLoginError("您还未登录");
    }

//    @ExceptionHandler(ShiroException.class)
//    public ServerResponse doHandleShiroException(
//            ShiroException e) {
//        if (e instanceof UnauthenticatedException) {
//            return ServerResponse.createUnLoginError("您还未登录");
//        } else if (e instanceof AuthorizationException) {
//            return ServerResponse.createUnAuthorizedError("您没有权限");
//        }
//        return null;
//    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(value = RException.class)
    public ServerResponse returnRunningException(RException e){
        System.out.println(e.getMsg());
        return ServerResponse.createExceptionMessage(e.getCode(),e.getMsg());
    }


}
